// 路由配置
const routes = {
    'store-monitor': '门店运营监控',
    'kpi-dashboard': 'KPI指标看板',
    'store-comparison': '店铺数据对比',
    'order-dispatch': '智能订单分配',
    'abnormal-orders': '异常订单处理',
    'refund-approval': '退款审批流程',
    'package-config': '套餐配置管理',
    'price-strategy': '价格策略调整',
    'batch-operations': '批量操作功能',
    'monitor-screen': '实时监控大屏',
    'sales-analysis': '销售分析报表'
};

// 主题切换
function toggleTheme() {
    const root = document.documentElement;
    const currentTheme = root.getAttribute('data-theme');
    const newTheme = currentTheme === 'dark' ? '' : 'dark';
    root.setAttribute('data-theme', newTheme);
}

// 初始化应用
function initApp() {
    // 绑定主题切换事件
    const themeSwitch = document.querySelector('.theme-switch');
    themeSwitch.addEventListener('click', toggleTheme);

    // 绑定菜单点击事件
    const menuItems = document.querySelectorAll('.submenu li');
    menuItems.forEach(item => {
        item.addEventListener('click', () => {
            const route = Object.entries(routes).find(([_, title]) => title === item.textContent)?.[0];
            if (route) {
                navigateTo(route);
            }
        });
    });

    // 初始化路由
    window.addEventListener('popstate', handleRouteChange);
    handleRouteChange();
}

// 路由处理
function navigateTo(route) {
    history.pushState(null, '', `#${route}`);
    handleRouteChange();
}

function handleRouteChange() {
    const route = window.location.hash.slice(1) || 'store-monitor';
    loadContent(route);
}

// 加载内容
async function loadContent(route) {
    let contentWrapper = document.querySelector('.content-wrapper');
    if (!contentWrapper) {
        contentWrapper = document.createElement('div');
        contentWrapper.className = 'content-wrapper';
        document.querySelector('.main-container').appendChild(contentWrapper);
    }

    // 首先隐藏所有内容
    document.querySelectorAll('.content-wrapper > div').forEach(div => {
        div.style.display = 'none';
    });

    try {
        // 检查并创建必要的DOM结构
        if (route === 'sales-analysis' && !document.querySelector('.sales-analysis')) {
            contentWrapper.innerHTML += `
                <div class="sales-analysis">
                    <div class="sales-analysis-header">
                        <h2 class="sales-analysis-title">销售分析报表</h2>
                        <div class="sales-analysis-filters">
                            <select class="time-range-select">
                                <option value="week">最近7天</option>
                                <option value="month">最近30天</option>
                                <option value="quarter">最近90天</option>
                            </select>
                            <select class="store-select">
                                <option value="all">全部门店</option>
                                <option value="store1">门店1</option>
                                <option value="store2">门店2</option>
                            </select>
                            <button class="export-button">导出报表</button>
                        </div>
                    </div>
                    <div class="sales-analysis-grid">
                        <div class="analysis-card">
                            <div class="analysis-card-header">
                                <h3 class="analysis-card-title">销售趋势分析</h3>
                            </div>
                            <div id="salesTrendChart" class="analysis-chart"></div>
                        </div>
                        <div class="analysis-card">
                            <div class="analysis-card-header">
                                <h3 class="analysis-card-title">商品销售排行</h3>
                            </div>
                            <div id="productRankingChart" class="analysis-chart"></div>
                        </div>
                        <div class="analysis-card">
                            <div class="analysis-card-header">
                                <h3 class="analysis-card-title">客户消费分析</h3>
                            </div>
                            <div id="customerAnalysisChart" class="analysis-chart"></div>
                        </div>
                        <div class="analysis-card">
                            <div class="analysis-card-header">
                                <h3 class="analysis-card-title">时段销售分布</h3>
                            </div>
                            <div id="timeDistributionChart" class="analysis-chart"></div>
                        </div>
                    </div>
                </div>
            `;
        }

        // 根据路由加载对应的模块内容
        switch(route) {
            case 'store-monitor':
                await import('./modules/store-monitor.js').then(module => {
                    const monitorDiv = document.querySelector('.store-monitor');
                    if (monitorDiv) monitorDiv.style.display = 'block';
                    module.initStoreMonitor();
                });
                break;
            case 'kpi-dashboard':
                await import('./modules/kpi-dashboard.js').then(module => {
                    module.initKPIDashboard();
                });
                break;
            case 'store-comparison':
                await import('./modules/store-comparison.js').then(module => {
                    module.initStoreComparison();
                });
                break;
            case 'order-dispatch':
                await import('./modules/order-assignment.js').then(module => {
                    module.initOrderAssignment();
                });
                break;
            case 'abnormal-orders':
                await import('./modules/order-exception.js').then(module => {
                    const orderException = new module.default();
                    orderException.init();
                });
                break;
            case 'refund-approval':
                await import('./modules/refund-approval.js').then(module => {
                    const refundApproval = new module.default();
                    refundApproval.init();
                });
                break;
            case 'package-config':
                await import('./modules/package-config.js').then(module => {
                    const packageConfig = new module.default();
                    packageConfig.init();
                });
                break;
            case 'price-strategy':
                await import('./modules/price-strategy.js').then(module => {
                    const priceStrategy = new module.default();
                    priceStrategy.init();
                });
                break;
            case 'batch-operations':
                await import('./modules/batch-operations.js').then(module => {
                    const batchOperations = new module.default();
                    batchOperations.init();
                });
                break;
            case 'monitor-screen':
                await import('./modules/monitor-dashboard.js').then(module => {
                    const dashboardDiv = document.querySelector('.monitor-dashboard');
                    if (dashboardDiv) dashboardDiv.style.display = 'block';
                    const monitorDashboard = new module.default();
                    monitorDashboard.init();
                });
                break;
            case 'sales-analysis':
                await import('./modules/sales-analysis.js').then(module => {
                    const salesAnalysisDiv = document.querySelector('.sales-analysis');
                    if (salesAnalysisDiv) {
                        // 确保之前的图表实例被销毁
                        const charts = ['salesTrendChart', 'productRankingChart', 'customerAnalysisChart', 'timeDistributionChart'];
                        charts.forEach(chartId => {
                            const chart = echarts.getInstanceByDom(document.getElementById(chartId));
                            if (chart) {
                                chart.dispose();
                            }
                        });
                        
                        salesAnalysisDiv.style.display = 'block';
                        // 等待DOM更新后再初始化
                        setTimeout(() => {
                            const salesAnalysis = new module.default();
                            salesAnalysis.init();
                        }, 0);
                    }
                });
                break;
            default:
                contentWrapper.innerHTML = `<h2>${routes[route] || '页面未找到'}</h2>`;
        }
    } catch (error) {
        console.error('加载内容失败:', error);
        contentWrapper.innerHTML = '<h2>加载失败</h2>';
    }
}

// 初始化应用
initApp();

// 初始化菜单点击事件
document.querySelectorAll('.submenu li').forEach(item => {
    item.addEventListener('click', () => {
        // 移除其他菜单项的active类
        document.querySelectorAll('.submenu li').forEach(i => i.classList.remove('active'));
        // 添加当前菜单项的active类
        item.classList.add('active');

        // 获取菜单文本
        const menuText = item.textContent.trim();

        // 根据菜单显示对应内容
        const route = Object.entries(routes).find(([_, title]) => title === menuText)?.[0];
        if (route) {
            navigateTo(route);
        }
    });
});